/*
 * @Author: OreoWang
 * @Email: ihc523@163.com
 * @Date: 2022-03-22 21:47:14
 * @LastEditors: OreoWang
 * @LastEditTime: 2022-04-26 17:17:26
 * @Description: 
 */

import { BehaviorComposite } from "./behavior-composite";
import { BehaviorEntity } from "./behavior-node-entity";
import { BehaviorStatus } from "./behavior-status";

export class BehaviorSequence extends BehaviorComposite {
    update(status: BehaviorStatus) {
        if(this.interrupt()){
            return super.update(status);
        }

        // 执行子节点
        let i = this.lastRunning >= 0 ? this.lastRunning : 0
        this.lastRunning = -1
        for (; i < this.children.length; i++) {
            status = this.children[i].execute()
            if (status === BehaviorStatus.Failure) {
                break
            } else if (status === BehaviorStatus.Success) {
                continue
            } else if (status === BehaviorStatus.Running) {
                this.lastRunning = i
                break
            }
        }

        return super.update(status);
    }

    interrupt(){
        let start = this.lastRunning >= 0 ? this.lastRunning : 0
        
        // 执行子节点中断评估
        if(this.interrupters.size>0 && start>0){
            // let status = BehaviorStatus.None;
            for(let i=0; i<start; i++){
                const child: BehaviorEntity = this.children[i] as BehaviorEntity;
                // const child = this.children[i];
                if(this.interrupters.has(child)){
                    const modify = child.checkCondition(child.statusCondition)
                    if(modify){
                        this.onInterrupt();
                        //中止原来正在执行中的任务
                        this.abort();
                        return true;
                    }
                    // status = child.execute();
                    // if (status === BehaviorStatus.Failure) {
                    //     break
                    // }
                    // else if (status === BehaviorStatus.Success) {
                    //     continue
                    // }
                    // else if (status === BehaviorStatus.Running) {
                    //     this.lastRunning = i
                    //     break
                    // }
                }
            }
            // if(status === BehaviorStatus.Success || status===BehaviorStatus.Running){
            //     this.onInterrupt();
            //     //中止原来正在执行中的任务
            //     this.abort();
            //     return true;
            // }
        }

        return false;
    }
}